define([
    'base',
    'msgTool',
    'bootstrapDialog',
    'bootstrapTable',
    'highcharts',
    'exporting',
    'highchartsCN',
    'jqViewer',
    'jqPrint',
    "css!global/plugins/viewer/viewer.min.css"
], function (base, msgTool, BootstrapDialog, highcharts, jqPrint) {
    //默认加载基础库
    base();

    /**
     * form表单转换成json
     */
    function getFormJson(form) {
        var data = {};
        var a = $(form).serializeArray();
        $.each(a, function () {
            if (data[this.name] !== undefined) {
                if (!data[this.name].push) {
                    data[this.name] = [data[this.name]];
                }
                data[this.name].push(this.value || '');
            } else {
                data[this.name] = this.value || '';
            }
        });
        return data;
    }

    /**
     * 添加拒绝信息到localStorage
     */
    function setRefuseMessage(key, value) {
        localStorage.setItem(key, value);
    }

    /**
     * 从localStorage获取拒绝信息
     */
    function getRefuseMessage() {
        var result = '';
        for (var i = 0; i < localStorage.length; i++) {
            result += localStorage.getItem(localStorage.key(i));
        }
        return result;
    }


    /**
     * 从localStorage清空拒绝信息
     */
    function clearRefuseMessage() {
        localStorage.clear();
    }

    return {
        marriageList: function (state) {


            var myTable = $('#dataList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: '/courtLawsuit/search'})
            };
            //table按需刷新动作
            var doAction = function (obj) {
                myTable.bootstrapTable('refresh', {url: state + '/api.json?pid=' + obj.id})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .claim': function (e, value, row) {      //认领
                    $.baseUtils.claimStatus({
                        row: row,
                        onText: '认领',
                        tableName: myTable,
                        nameText: '婚姻诉讼',
                        nameValue: row.plaintiffName,
                        //点击认领后，要将状态改为处理中，所以调用此接口。
                        url: '../courtLawsuit/accept?lawsuitId='+row.id
                    });
                },

                'click .handle': function (e, value, row) {        //审核
                    window.location.href = "details?lawsuitId="+ row.id +'&site=apply_handle'
                },

                'click .print': function (e, value, row) {
                    window.location.href = "../print/" + row.id;
                },

                'click .status': function (e, value, row) {
                    $.baseUtils.oneStatus({
                        row: row,
                        tableName: myTable,
                        onText: '恢复',
                        offText: '取消',
                        nameText: '婚姻诉讼',
                        nameValue: row.companyName,
                        url: '../status/action'
                    });
                },
                'click .delete': function (e, value, row) {     //删除
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '婚姻诉讼',
                        nameValue: row.plaintiffName,
                        url: '../courtLawsuit/deleteLawsuit?lawsuitId='+row.id
                    });
                },
                'click .info': function (e, value, row) {   //详情
                    window.location.href = "details?lawsuitId="+ row.id+'&site=apply_view';
                },

            };

            //table表格
            myTable.bootstrapTable({
                url: '/courtLawsuit/' + state, // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [
                    {
                        field: 'id',
                        title: '诉讼编号',
                        width: '5%'
                    }, {
                        field: 'plaintiffName',
                        title: '原告和被告',
                        width: '25%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-hashtag text-primary" aria-hidden="true"></i>原告：&emsp;<b>' + row.plaintiffName + '</b><br /><i class="fa fa-map-marker text-primary" aria-hidden="true"></i>被告：&emsp;<span class="text text-muted">' + row.accusedName + '</span>'
                        }
                    },
                    {
                        field: 'createName',
                        title: '申请时间',
                        width: '15%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-user" aria-hidden="true"></i>&emsp;' + value + '<br /><i class="fa fa-clock-o" aria-hidden="true"></i>&emsp;' + row.createTime
                        }
                    }, {
                        field: 'updateName',
                        title: '更新信息',
                        width: '15%',
                        formatter: function (value, row, index) {
                            var updateTime = row.updateTime;
                            if (updateTime == null) {
                                updateTime = '未更新';
                            }
                            return '<i class="fa fa-user" aria-hidden="true"></i>&emsp;' + value + '<br /><i class="fa fa-clock-o" aria-hidden="true"></i>&emsp;' + updateTime
                        }
                    }, {
                        field: 'stage',
                        title: '处理进度',
                        align: 'center',
                        width: '5%',
                        //申请状态（0未提交暂存；1待审核；2审核中；3审核拒绝被退回；4审核通过；8放弃作废)
                        formatter: function (value,row) {
                            value = row.stage;
                            if (value === 0) {
                                return "<span class=\"label label-warning\"><i class=\"fa fa-lock\" aria-hidden=\"true\"></i>&nbsp;已提交</span>";
                            } else if (value === 1) {
                                return "<span class=\"label label-success\"><i class=\"fa fa-retweet\" aria-hidden=\"true\"></i>&nbsp;审核中</span>";
                            } else if (value === 2) {
                                return "<span class=\"label label-primary\"><i class=\"fa fa-reply\" aria-hidden=\"true\"></i>&nbsp;已办结</span>";
                            } else if (value === 3) {
                                return "<span class=\"label label-danger\"><i class=\"fa fa-check\" aria-hidden=\"true\"></i>&nbsp;已退回</span>";
                            } else {
                                return "<span class=\"label label-inverse\">未知</span>";
                            }

                        }
                    },
                    {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        width: '25%',
                        formatter: operateFormatter,
                        events: operateEvents
                    }
                ]
            });

            var tableSearch = function () {
                myTable.bootstrapTable('refresh', {url: '/courtLawsuit/search'})
            };
            //搜索刷新
            $('#search').on('click', function () {
                tableSearch();
            });

            //toolbar按钮相应事件
            //新增
            $(".toolbar-save").on('click', function () {
                winModal("新增", null);
            });
            //刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });

            //批量修改状态
            $(".toolbar-batchStatus").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [], names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.companyName);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '工商申请',
                        nameValue: names,
                        url: '../status/batchAction'
                    });
                } else {
                    msgTool.error("请选择虽少一条记录后再操作", "信息提示");
                }

            });


            //搜索参数传递
            function queryParams(params) {
                params.search = $("#searchValue").val();
                params.companyAddress = $("#companyAddress").val();
                params.applyStatus = $("#applyStatus").val();
                params.createTime = $("#createTime").val();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    createTime: params.createTime,
                    applyStatus: params.applyStatus,
                    companyAddress: params.companyAddress,
                    search: params.search
                };
            }

            //回显
            function responseHandler(res) {
                return res.rows;
            }


            //模态框
            function winModal(title, row) {
                BootstrapDialog.show({
                    type: BootstrapDialog.TYPE_DEFAULT,
                    tabindex: null,//解决select2搜索框失去焦点的问题
                    title: title,
                    closable: true,	//关闭箭头启动
                    closeByBackdrop: false,	//点击空白不消失
                    closeByKeyboard: true,//ESC取消禁用
                    message: $('<div></div>').load('../save/form.html'),
                    data: {
                        'row': row
                    },
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white cancel',
                        icon: 'fa fa-times',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: '提交' + title,
                        //hotkey: 13,//回车提交
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialog) {
                            //返回验证结果
                            var flag = false;
                            flag = $("#winModal").validate().form();
                            if (flag) {
                                $.baseUtils.ajax({
                                    dialog: dialog,
                                    url: '../save/action',
                                    data: $("#winModal").serialize(),
                                    text: "保存",
                                    isTable: true,
                                    tableName: '#flowList',
                                    isDialog: true
                                })
                            }
                        }
                    }],
                    onshown: function (dialog) {
                        if (row != null) {
                            $('#id').val(row.id);
                            $('#companyName').val(row.companyName);
                            $('#itemCode').val(row.itemCode);
                        }
                    }
                });
            }
        },
        template: function (flowId) {
            //添加工商申请步骤
            $("#addStep").on('click', function () {
                var length = $("form").length + 1;
                $("#step-box").append("<form class=\"form-horizontal\" name=\"flowTemplateForm\" id=\"flowTemplate_" + length + "\" method=\"post\" role=\"form\"><input value=\"" + flowId + "\" name=\"flowId\" type=\"hidden\"><div class=\"panel panel-default\"><div class=\"panel-heading\"><b class=\"text step-title\">工商申请步骤" + length + "：</b><div class=\"pull-right\"><button onclick=\"$(this).parents('.panel').remove()\" class=\"btn btn-danger\">&nbsp;删除&nbsp;</button></div></div><div class=\"panel-body\"><div class=\"form-group\"><div class=\"col-sm-3\"><label class=\"control-label\">步骤名称：</label><input name=\"stepName\" class=\"form-control\" type=\"text\" required aria-required=\"true\" maxlength='30' placeholder=\"请输入步骤名称\"></div><div class=\"col-sm-3\"><label class=\"control-label\">上个部门小组编号：</label><input name=\"lastOrgId\" class=\"form-control\" type=\"number\" placeholder=\"请输入上个部门小组编号\" required='required'></div><div class=\"col-sm-3\"><label class=\"control-label\">当前部门小组编号：</label><input name=\"orgId\" class=\"form-control\" type=\"number\" required aria-required=\"true\" placeholder=\"请输入当前部门小组编号\"></div><div class=\"col-sm-3\"><label class=\"control-label\">下个部门小组编号：</label><input name=\"nextOrgId\" class=\"form-control\" type=\"number\" placeholder=\"请输入下个部门小组编号\" required='required'></div></div><div class=\"form-group\"><div class=\"col-sm-3\"><label class=\"control-label\">节点类型：</label><select name=\"nodeType\" class=\"form-control\"><option value=\"0\" selected>普通节点</option><option value=\"1\">开始节点</option><option value=\"2\">结束节点</option></select></div><div class=\"col-sm-9\"><label class=\"control-label\">附加参数：</label><input name=\"attrs\" class=\"form-control\" type=\"text\" required aria-required=\"true\" placeholder=\"请输入附加参数\"></div></div></div></div></form>");
            });
            //提交工商申请
            $("#doSubmit").on('click', function () {
                    var dataFormStatus = false;
                    var form = $("form[name='flowTemplateForm']");
                    $.each(form, function () {
                        dataFormStatus = $(this).validate().form();
                    });
                    dataFormStatus = true;
                    if (dataFormStatus) {
                        var length = form.length;
                        //定义要传递的数组
                        var flowTemplateList = [];
                        for (var i = 1; i <= length; i++) {
                            var formJson = getFormJson($("#flowTemplate_" + i));
                            flowTemplateList.push(formJson);
                        }
                        $.ajax({
                            url: "/flow/template/save/action",
                            type: 'POST',
                            data: JSON.stringify(flowTemplateList),
                            dataType: "JSON",
                            contentType: 'application/json;charset=utf-8',
                            beforeSend: function () {
                                //触发ajax请求开始时执行
                                $("#doSubmit").text('提交中...');
                                $("#doSubmit").attr('disabled', 'disabled');
                            },
                            success: function (data) {
                                if (data.success) {
                                    window.location.href = "/flow/view/index";
                                } else {
                                    msgTool.error(data.msg);
                                }
                            },
                            error: function (error) {
                                msgTool.error("操作失败，请刷新当前页面后重试！");
                            },
                            complete: function () {
                                $("#doSubmit").text("保存");
                                $("#doSubmit").removeAttr('disabled');
                            }
                        });
                    }
                }
            );
        },
        marriageView: function () {

            $("input[name='auditSelected']").on('click', function () {
                if ($("input[name='auditSelected']:checked")) {

                    //字号判断
                    if ($("#allBrandDisabled").is(':checked')) {
                        $.each($(".companyBrandList").find("input[name='auditSelected']"), function (k, v) {
                            $(v).attr("checked", false);
                            $(v).attr("disabled", "disabled");
                        })
                    } else {
                        $.each($(".companyBrandList").find("input[name='auditSelected']"), function (k, v) {
                            $(v).removeAttr("disabled");
                        })
                    }

                    //股东判断
                    if ($("#holderPictureDisabled").is(':checked')) {
                        $.each($("#sharehoderList").find(".holderPicture > input[name='auditSelected']"), function (k, v) {
                            $(v).attr("checked", false);
                            $(v).attr("disabled", "disabled");
                        })
                    } else {
                        $.each($("#sharehoderList").find(".holderPicture > input[name='auditSelected']"), function (k, v) {
                            $(v).removeAttr("disabled");
                        })
                    }

                    if ($("#holderInfoDisabled").is(':checked')) {
                        $.each($("#sharehoderList").find(".holderInfo > input[name='auditSelected']"), function (k, v) {
                            $(v).attr("checked", false);
                            $(v).attr("disabled", "disabled");
                        })
                    } else {
                        $.each($("#sharehoderList").find(".holderInfo > input[name='auditSelected']"), function (k, v) {
                            $(v).removeAttr("disabled");
                        })
                    }


                    //成员判断
                    if ($("#memberPictureDisabled").is(':checked')) {
                        $.each($("#memberList").find(".memberPicture > input[name='auditSelected']"), function (k, v) {
                            $(v).attr("checked", false);
                            $(v).attr("disabled", "disabled");
                        })
                    } else {
                        $.each($("#memberList").find(".memberPicture > input[name='auditSelected']"), function (k, v) {
                            $(v).removeAttr("disabled");
                        })
                    }

                    if ($("#memberInfoDisabled").is(':checked')) {
                        $.each($("#memberList").find(".memberInfo > input[name='auditSelected']"), function (k, v) {
                            $(v).attr("checked", false);
                            $(v).attr("disabled", "disabled");
                        })
                    } else {
                        $.each($("#memberList").find(".memberInfo > input[name='auditSelected']"), function (k, v) {
                            $(v).removeAttr("disabled");
                        })
                    }


                    //删除已选信息
                    clearRefuseMessage();

                    var auditSelected = $("#tabs-container").find("input[name='auditSelected']:checked");
                    $.each(auditSelected, function (k, v) {
                        setRefuseMessage(k, $(v).data("message") + "\n");
                    });
                    $("#auditMessage").val(getRefuseMessage());
                }
            });

            /**
             * 经营范围编辑开关
             */
            $("#changeBusinessScope").click(function () {
                if ($(this).is(":checked")) {
                    $("#businessScope").removeAttr("disabled");
                }
                else {
                    $("#businessScope").attr("disabled", "disabled");
                }
            });
             /**
              * 注册地址开关
              * */
             $("#auditSelect").click(function () {
                 if ($(this).is(":checked")) {
                     $("#companyAddress").removeAttr("disabled");
                 }
                 else {
                     $("#companyAddress").attr("disabled", "disabled");
                 }
             });


            $('#cardUrl').viewer({
                navbar: false,
                title: false
            });

            $('#cardVerso').viewer({
                navbar: false,
                title: false
            });

            $('#proof').viewer({
                navbar: false,
                title: false
            });

            //协议证照
            $('#businessScopeImage').viewer({
                navbar: false,
                title: false
            });
            //身份证
            $('.IDcard').viewer({
                navbar: false,
                title: false
            });

            $("#doSubmit").on('click', function () {
                    var data = {
                        lawsuitId: $("#id").val(),
                        stage: $("input[name='stage']:checked").val(),
                        suggest: $("#auditMessage").val()
                    };
                    $.ajax({
                        url: "/courtLawsuit/audit",
                        type: 'POST',
                        data: data,
                        dataType: "JSON",
                        beforeSend: function () {
                            //触发ajax请求开始时执行
                            $("#doSubmit").text('提交中...');
                            $("#doSubmit").attr('disabled', 'disabled');
                        },
                        success: function (data) {
                            if (data.success) {
                                msgTool.success(data.msg);
                                window.location.href = "/courtLawsuit/assessors";
                            } else {
                                msgTool.error(data.msg);
                            }
                        },
                        error: function () {
                            msgTool.error("操作失败，请刷新当前页面后重试！");
                        },
                        complete: function () {
                            $("#doSubmit").text("提交审核");
                            $("#doSubmit").removeAttr('disabled');
                        }
                    });
                });

        },
        print: function () {
            /**
             * 打印
             * @param contentNode
             */
            function print(contentNode) {
                if (!!window.ActiveXObject || "ActiveXObject" in window) { //是否ie
                    remove_ie_header_and_footer();
                }
                $(contentNode).print();
            }

            //打印公司登记（备案）信息表
            $("#print_company").on('click', function () {
                print("#print_company_content");
            });
            //打印股东信息
            $("#print_shareholder").on('click', function () {
                print("#print_shareholder_content");
            });
            //打印法人信息
            $("#print_legal").on('click', function () {
                print("#print_legal_content");
            });
            //打印董事、监事、经理信息
            $("#print_manager").on('click', function () {
                print("#print_manager_content");
            });
            //打印股东（发起人）出资情况
            $("#print_capital").on('click', function () {
                print("#print_capital_content");
            });
            //打印财务负责人信息
            $("#print_financial").on('click', function () {
                print("#print_financial_content");
            });
            //打印联络员信息
            $("#print_contact").on('click', function () {
                print("#print_contact_content");
            });
            //打印指定代表或者共同委托人代理人授权委托人
            $("#print_entrust").on('click', function () {
                print("#print_entrust_content");
            });
            //打印承诺书
            $("#print_promise").on('click', function () {
                print("#print_promise_content");
            });
            //打印股东决定
            $("#print_holder_decision").on('click', function () {
                print("#print_holder_decision_content");
            });
            //打印首次股东会决议
            $("#print_holders_decision").on('click', function () {
                print("#print_holders_decision_content");
            });
            //打印公司章程
            $("#print_rule_decision").on('click', function () {
                print("#print_rule_decision_content");
            });
            //打印多人章程
            $("#print_rules_decision").on('click', function () {
                print("#print_rules_decision_content");
            });


        },
        report: function (data, title) {
            var chart = Highcharts.chart('container', {
                title: {
                    text: title + "报表统计"
                },
                xAxis: {
                    categories: ['未提交', '待认领', '办理中', '退回修改', '审核通过', '取消办理']
                },
                yAxis: {
                    allowDecimals: false,
                    title: {
                        text: '数量（件）'
                    }
                },
                series: [{
                    type: 'column',
                    name: '数量',
                    colorByPoint: true,
                    data: [data.sumNothingTask, data.sumClaimTask, data.sumHandleTask, data.sumRefuseTask, data.sumPassTask, data.sumInvalidTask],
                    showInLegend: false
                }]
            });

        }
    };
});






